/*
 * @Author: 曹捷
 * @Date: 2020-08-03 17:09:48
 * @LastEditors: 曹捷
 * @LastEditTime: 2020-08-03 20:14:17
 * @Description: 构建 pages.json
 * 支持uniapp 条件编译
 * 
    {
        "iftype": "ifndef APP-PLUS"
    },
 */
const fs = require('fs')
const path = require('path')
let baseConfig = {
    baseUrl: './../../'
}
const router = require(baseConfig.baseUrl + 'router/index.js')

// 将子路由模块配置文件转化为 uniapp 配置文件格式
const buildRouter = route => {
    const res = []
    const { baseUrl, children } = route
    children.forEach(i => {
        const obj = {
            path: baseUrl + i.path,
            style: {
                navigationBarTitleText: i.name
            }
        }
        Object.keys(i).forEach(ii => {
            !['path', 'name'].includes(ii) && (obj[ii] = i[ii])
        })
        res.push(obj)
    })
    return res
}

// 自动加载 './modules' 目录子路由配置文件
const getRouter = () => {
    const srcPath = path.resolve(__dirname, baseConfig.baseUrl + 'router/modules')
    const result = fs.readdirSync(srcPath)
    let router = []
    result.forEach(r => {
        const route = require(baseConfig.baseUrl + 'router/modules/' + r)
        router = [...router, ...buildRouter(route)]
    })
    return router
}

// 构建 pages 并写入 pages.json 文件
router.pages = getRouter()
let jsons = JSON.stringify(router, null, '  ')
// 对于 条件编译 采用对象 iftype 匹配替换
// ` {
//     "iftype": "ifndef APP-PLUS"
//   },
//   {
//     "pagePath": "pages/tabbar/question/question",
//   {
//     "iftype": "endif"
//   },`
jsons = jsons.replace(/\{\n.+iftype\"\:\s+\"(.+)\"\n\s+\}\,/g, '// #$1')
jsons = jsons.replace(/\/ue/g, '\\ue')

fs.writeFile(
    __dirname + baseConfig.baseUrl + 'pages.json',
    // 我这边是用两个空格来缩进 pages.json，如果喜欢制表符，第三个参数更换你为 \t 即可
    jsons,
    e => e ? console.error(e) : console.log('pages.json 配置文件更新成功')
)